home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 2 / Atari Mega Archive CD - Volume 2.iso / minix / up1510b.tgz / up1510b / src / commands / lpr.c < prev    next >
C/C++ Source or Header  |  1990-07-15  |  2KB  |  111 lines

  1. /* lpr - line printer front end        Author: Andy Tanenbaum */
  2.  
  3. #include <errno.h>
  4. #include <sys/types.h>
  5. #include <fcntl.h>
  6.  
  7. #define BLOCK 1024
  8.  
  9. char in_buf[BLOCK], out_buf[BLOCK];
  10. int cur_in, in_count, out_count, column;
  11.  
  12. main(argc, argv)
  13. int argc;
  14. char *argv[];
  15. {
  16. /* This program copies files to the line printer.  It expands tabs and converts
  17.  * line feeds to carriage returns + line feeds.
  18.  */
  19.  
  20.   int i, fd;
  21.  
  22.   close(1);
  23.   if (open("/dev/lp", O_WRONLY) < 0) {
  24.     std_err("lpr: can't open /dev/lp\n");
  25.     exit(1);
  26.   }
  27.   if (argc == 1) {
  28.     copy(0);        /* standard input only */
  29.   } else {
  30.     for (i = 1; i < argc; i++) {
  31.         if ((fd = open(argv[i], O_RDONLY)) < 0) {
  32.             std_err("lpr: can't open ");
  33.             std_err(argv[1]);
  34.             std_err("\n");
  35.             exit(1);
  36.         } else {
  37.             copy(fd);
  38.             close(fd);
  39.             cur_in = 0;
  40.             in_count = 0;
  41.         }
  42.     }
  43.   }
  44.   exit(0);
  45. }
  46.  
  47.  
  48. copy(fd)
  49. int fd;
  50. {
  51. /* Print a file, adding carriage returns and expanding tabs. */
  52.  
  53.   char c;
  54.  
  55.   while (1) {
  56.     if (cur_in == in_count) {
  57.         in_count = read(fd, in_buf, BLOCK);
  58.         if (in_count == 0) {
  59.             flush();
  60.             return;
  61.         }
  62.         cur_in = 0;
  63.     }
  64.     c = in_buf[cur_in++];
  65.     if (c == '\n') {
  66.         putc('\r');
  67.         putc('\n');
  68.     } else if (c == '\t') {
  69.         do {
  70.             putc(' ');
  71.         } while (column & 07);
  72.     } else
  73.         putc(c);
  74.   }
  75. }
  76.  
  77. putc(c)
  78. char c;
  79. {
  80.   out_buf[out_count++] = c;
  81.   if (c == '\n')
  82.     column = 0;
  83.   else
  84.     column++;
  85.   if (out_count == BLOCK) {
  86.     flush();
  87.   }
  88. }
  89.  
  90. flush()
  91. {
  92.   int n, count = 0;
  93.  
  94.   if (out_count == 0) return;
  95.   while (1) {
  96.     n = write(1, out_buf, out_count);
  97.     if (n == out_count) break;
  98.     if (n != EAGAIN) {
  99.         std_err("Printer error\n");
  100.         exit(1);
  101.     }
  102.     if (count > 5) {
  103.         std_err("Printer keeps returning busy status\n");
  104.         exit(1);
  105.     }
  106.     count++;
  107.     sleep(1);
  108.   }
  109.   out_count = 0;
  110. }
  111.